import os
import re

def load_replacements(properties_file):
    """从 lang_zn.properties 文件中加载替换键值对"""
    replacements = {}
    try:
        with open(properties_file, 'r', encoding='utf-8') as file:
            for line in file:
                # 跳过空行和注释行
                line = line.strip()
                if not line or line.startswith('#'):
                    continue

                # 解析 key=value 格式
                if '=' in line:
                    key, value = line.split('=', 1)
                    replacements[value.strip()] = key.strip()
    except Exception as e:
        print(f"Error reading {properties_file}: {e}")
    return replacements

def replace_in_file(file_path, replacements):
    """在文件中根据替换字典替换完全匹配的值"""
    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

        # 应用替换（仅替换完全匹配的值）
        for target, replacement in replacements.items():
            content = re.sub(rf'\b{re.escape(target)}\b', replacement, content)

        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)
        print(f"Processed: {file_path}")
    except Exception as e:
        print(f"Error processing {file_path}: {e}")

if __name__ == "__main__":
    properties_file = r"E:\\Project\\pipayshoh-dev\\common-api\\src\\main\\resources\\lang\\lang_zn.properties"

    # 检查 lang_zn.properties 文件是否存在
    if not os.path.exists(properties_file):
        print(f"Error: {properties_file} not found.")
        exit(1)

    # 加载替换键值对
    replacements = load_replacements(properties_file)
    if not replacements:
        print("No replacements found in lang_zn.properties.")
        exit(1)

    # 获取当前目录
    current_directory = os.getcwd()

    # 遍历当前目录的所有文件
    for root, _, files in os.walk(current_directory):
        for file_name in files:
            # 跳过 lang_zn.properties 和 js.py 文件
            if file_name in ['lang_zn.properties', 'replace.py']:
                continue

            file_path = os.path.join(root, file_name)

            # 排除非文本文件（如二进制文件）
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    file.read()
            except:
                print(f"Skipped non-text file: {file_path}")
                continue

            # 替换内容
            replace_in_file(file_path, replacements)

    print("Replacement complete.")